package com.atguigu.rabbitmq.workqueue;

import com.atguigu.rabbitmq.utlis.RabbitMQUtils;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;

/**
 * 定义工作线程，即消费者，从rabbitmq队列中消费消息
 */

@SuppressWarnings("all")
public class Worker extends Thread {

    private String workID;

    private final String QUEUE_NAME = "HELLO";


    public Worker(String workID) {
        this.workID = workID;
    }

    private DeliverCallback deliverCallback = ((consumerTag, message) -> {
        System.out.println("worker-" + workID + " 从rabbitm队列-" + QUEUE_NAME + "中消费消息：" + new String(message.getBody()));
    });

    private CancelCallback cancelCallback = (consumerTag -> {
        System.out.println("worker-" + workID + "消费被中断");
    });

    @Override
    public void run() {
        Channel channel = RabbitMQUtils.getChannel();

        try {
            // 生成一个rabbitmq队列
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);

            System.out.println("worker-" + workID + "等待消费");
            channel.basicConsume(QUEUE_NAME, true, deliverCallback, cancelCallback); // 如果rabbitmq队列中没有消息会阻塞
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Worker worker = new Worker("001");
        worker.start();
    }
}
